// Copyright 2025 Teamgram Authors
//  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: teamgramio (teamgram.io@gmail.com)
//

package core

import (
	"github.com/teamgram/proto/mtproto"
	"github.com/teamgram/teamgram-server/app/messenger/msg/internal/dal/dataobject"
	"github.com/teamgram/teamgram-server/app/messenger/msg/msgtransfer/msgtransfer"
	"github.com/teamgram/teamgram-server/app/messenger/sync/sync"
)

// MsgtransferSendMessageToOutbox
// msgtransfer.sendMessageToOutbox flags:# user_id:long auth_key_id:long peer_type:int peer_id:long message:Vector<OutboxMessage> users:flags.1?Vector<User> chats:flags.2?Vector<Chat> = MessageBoxList;
func (c *MsgtransferCore) MsgtransferSendMessageToOutbox(in *msgtransfer.TLMsgtransferSendMessageToOutbox) (*mtproto.MessageBoxList, error) {
	//boxList := in.GetBoxList()
	outBoxList := make([]*mtproto.MessageBox, 0, len(in.GetMessage()))
	for _, inBox := range in.GetMessage() {
		outBox, err := c.svcCtx.Dao.SendUserMessageV4(c.ctx, in.UserId, in.PeerId, inBox, true)
		if err != nil {
			c.Logger.Errorf("sendMessageToOutbox - error: %v", err)

			return nil, err
		}
		//if isUseV3 {
		//	inBox.Pts = c.svcCtx.Dao.IDGenClient2.NextPtsId(c.ctx, in.FromId)
		//	inBox.PtsCount = 1
		//}

		err = c.svcCtx.Dao.SendMessageToOutboxV1(
			c.ctx,
			in.UserId,
			mtproto.MakePeerUtil(in.PeerType, in.PeerId),
			outBox)
		if err != nil {
			// TODO: handle error
			c.Logger.Errorf("inbox.sendUserMessageToInboxV2 - error: %v", err)
			return nil, err
		}

		// TODO: handle sendToSelfUser
		if in.PeerType == mtproto.PEER_USER && in.UserId == in.PeerId {
			peer2 := outBox.GetMessage().GetSavedPeerId()
			if peer2 == nil {
				c.Logger.Errorf("inbox.sendUserMessageToInboxV2 - error: sendToSelfUser")
			} else {
				peer := mtproto.FromPeer(peer2)
				_, _, _ = c.svcCtx.Dao.SavedDialogsDAO.InsertOrUpdate(
					c.ctx,
					&dataobject.SavedDialogsDO{
						UserId:     in.UserId,
						PeerType:   peer.PeerType,
						PeerId:     peer.PeerId,
						Pinned:     0,
						TopMessage: outBox.GetMessageId(),
					})
			}
		}

		_, err = c.svcCtx.Dao.SyncClient.SyncUpdatesNotMe(c.ctx, &sync.TLSyncUpdatesNotMe{
			UserId:        in.UserId,
			PermAuthKeyId: in.AuthKeyId,
			Updates: mtproto.MakeUpdatesByUpdatesUsersChats(
				in.Users,
				in.Chats,
				mtproto.MakeTLUpdateNewMessage(&mtproto.Update{
					Message_MESSAGE: outBox.GetMessage(),
					Pts_INT32:       outBox.Pts,
					PtsCount:        outBox.PtsCount,
				}).To_Update()),
		})

		outBoxList = append(outBoxList, outBox)
	}

	return mtproto.MakeTLMessageBoxList(&mtproto.MessageBoxList{
		BoxList: outBoxList,
	}).To_MessageBoxList(), nil
}
